package com.ytrsoft.controller;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.ytrsoft.response.ResponseEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

@RestController
@RequestMapping("/qrcode")
@Tag(name = "二维码接口")
public class QRCodeController {

    @GetMapping("/gen/{content}/{width}/{height}")
    @Operation(summary = "生成")
    public ResponseEntity<Void> gen(HttpServletResponse response, @PathVariable String content, @PathVariable Integer width, @PathVariable Integer height) {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.MARGIN, 0);
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            response.setContentType("image/png");
            response.setHeader("Content-Disposition", "inline; filename=\"qrcode.png\"");
            MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.succeed();
    }

    @PostMapping("/dec")
    @Operation(summary = "二维码识别")
    public ResponseEntity<String> dec(@RequestParam("file") MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            BufferedImage image = ImageIO.read(in);
            BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, hints);
            String content = result.getText();
            return ResponseEntity.succeed(content);
        } catch (NotFoundException e) {
            throw new RuntimeException("请检查二维码是否有效");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
